package com.xiangge.aliyun.aliyuntest.controller;

import com.xiangge.aliyun.aliyuntest.util.ResponseUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


@RestController
@RequestMapping("/project/")
@Api(tags = "leading项目部署")
public class ProjectLoadingController {
    @PostMapping("/loading")
    @ApiOperation(value = "leading项目部署", notes = "leading项目部署", produces = "application/json")
    public Object loading(@RequestBody String projectName, HttpServletResponse response) {
        Runtime runtime = Runtime.getRuntime();
        String commend = "sh /usr/local/src/java_project/aliyun/start.sh";
        try {
            Process proc = Runtime.getRuntime().exec(commend);
            /**
             * 可执行程序的输出可能会比较多，而运行窗口的输出缓冲区有限，会造成waitFor一直阻塞。
             * 解决的办法是，利用Java提供的Process类提供的getInputStream,getErrorStream方法
             * 让Java虚拟机截获被调用程序的标准输出、错误输出，在waitfor()命令之前读掉输出缓冲区中的内容。
             */
            String flag;
            BufferedReader bufferedReader =
                    new BufferedReader(new InputStreamReader(proc.getInputStream()));
            while ((flag = bufferedReader.readLine()) != null) {
                if (flag.contains("9080")) {
                    return ResponseUtil.ok();
                }
                System.out.println("result ---- " + flag);
            }
            bufferedReader.close();
            response.sendRedirect("http://106.15.238.66:9080/");
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseUtil.fail();
        }

        return ResponseUtil.ok();
    }
}
